/**
 * 文档浏览器 文档上传有关操作
 */
import {ref} from "vue";
import {message} from "@/utils/ElmessasgeUtils";
import {uploadFileToBucket} from "@/api/documentManage/minioManager2";
import {currentBucketName} from "@/views/documentManager/components/ts/FileBrowser";


export const uploading = ref(false);
export const isDragging = ref(false);
export const uploadProgress = ref(0);

export const selectedFile = ref<File | null>(null);
export const customFileName = ref('');


export const clipboardData = ref<Blob | null>(null);
export const clipboardFileName = ref('clipboard-image.png');

// 处理拖放相关事件
export const dragOver = (event: DragEvent) => {
    event.preventDefault();
    isDragging.value = true;
};

export const dragLeave = () => {
    isDragging.value = false;
};

// 验证并设置文件
export const validateAndSetFile = (file: File) => {
    // 文件大小限制100MB
    const maxSize = 2 * 1024 * 1024 * 1024;

    if (file.size > maxSize) {
        message('文件大小不能超过2GB', 'error');
        return;
    }

    selectedFile.value = file;
};

// 上传文件时拖动文件到框内
export const handleDropFile = (event: DragEvent) => {
    event.preventDefault();
    isDragging.value = false;

    if (event.dataTransfer?.files && event.dataTransfer.files.length > 0) {
        if (event.dataTransfer.files.length > 1) {
            message('每次只能上传一个文件', 'error');
            return;
        }
        validateAndSetFile(event.dataTransfer.files[0]);
    }
};

// 处理文件选择
export const handleFileSelect = (event: Event) => {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files.length > 0) {
        validateAndSetFile(input.files[0]);
    }
};

// 重置剪切板相关状态
export const resetUploadState = () => {
    selectedFile.value = null;
    customFileName.value = '';
    uploadProgress.value = 0;
    uploading.value = false;
    isDragging.value = false;
    clipboardData.value = null;
};

// 添加处理粘贴事件的方法
export const handlePastePic = async (event: ClipboardEvent) => {
    // 如果正在上传，则忽略
    if (uploading.value) return;

    // 重置上传状态
    resetUploadState();

    // 检查剪切板中是否有图片
    const items = event.clipboardData?.items;
    if (!items) return;

    for (let i = 0; i < items.length; i++) {
        const item = items[i];
        if (item.type.indexOf('image') !== -1) {
            // 获取图片数据
            const blob = item.getAsFile();
            if (blob) {
                clipboardData.value = blob;

                // 生成一个带时间戳的文件名
                const timestamp = new Date().getTime();
                clipboardFileName.value = `paste-${timestamp}.${blob.type.split('/')[1] || 'png'}`;
                // 设置选中的文件
                selectedFile.value = new File([blob], clipboardFileName.value, {
                    type: blob.type,
                    lastModified: Date.now()
                });

                // 自动填充文件名
                customFileName.value = clipboardFileName.value
                // 显示提示
                message('已从剪切板获取图片，点击上传按钮即可上传', 'success');
            }
            break;
        }
    }
};


// 确认上传文件
export const confirmUploadFile = async (currentPath: string, callback: Function) => {
    if (!selectedFile.value || uploading.value) return;

    const formData = new FormData();
    formData.append('file', selectedFile.value);

    uploading.value = true;
    uploadProgress.value = 0;

    try {
        // 使用axios的onUploadProgress回调更新进度
        const config = {
            onUploadProgress: (progressEvent: ProgressEvent) => {
                if (progressEvent.total) {
                    uploadProgress
                        .value = Math.round(
                        (progressEvent.loaded * 100) / progressEvent.total
                    );
                }
            }
        };

        let response = await uploadFileToBucket(currentBucketName.value, currentPath, formData, config, customFileName.value)
        if (response.data.code === 200) {
            callback();
            message("上传文件成功: ", 'success')
        } else {
            message('上传失败，请重试', 'error');
        }
    } catch (err: any) {
        console.error('上传错误:', err);
        message(err.response?.data?.message || err.message || '上传过程中发生错误', 'error');
    } finally {
        uploading.value = false;
    }
};


export async function uploadTextAsFile(
    textContent: string,
    path: string,
    fileName?: string,
) {
    const formData = new FormData();

    // 将文本转换为 Blob 对象
    const blob = new Blob([textContent], {type: 'text/plain'});

    // 如果没有提供文件名，使用默认文件名
    const actualFileName = fileName || `text_${Date.now()}.txt`;

    // 创建 File 对象
    const file = new File([blob], actualFileName, {type: 'text/plain'});

    formData.append('file', file);
    try {
        let res = await uploadFileToBucket(currentBucketName.value, path, formData, {}, actualFileName)
        if (res.data.code === 200) {
            message("保存成功", 'success')
        } else {
            message("保存失败: " + res.data.msg, 'error')
        }


    } catch (error) {
        message("保存失败", 'success')
    }
}